<script setup lang="ts">
import { addMilstdApi } from '@@/apis/resources/milstd';
import { addModelApi } from '@@/apis/resources/three-model';
import { AddBaseInfo } from '@@/apis/resources/types';
import { ElMessage, ElMessageBox, FormRules, genFileId, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus';
import { isEmpty } from 'lodash';
import { getThreeDataApi, updateThreeDataApi } from '@@/apis/Three-model'
import { getMilitaryDataDetailApi, updateMilitaryDataApi } from '@@/apis/military'
import thumbUpload from "./thumbFile.vue"
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import { cloneDeep, isEqual } from "lodash-es"
// 导入缩略图生成器
import {
  thumbnailGenerator,
  generateThumbnailFromFile,
  generateThumbnailFromUrl,
  generateThumbnailFromFileWithProgress,
  generateThumbnailFromUrlWithProgress
} from './generateThumbnailFromUrl';

const DEFAULT_FORM_DATA: AddBaseInfo = {
  name: "",
  code: undefined,
  remark: undefined,
  file: undefined
}

// 表单和状态相关引用
const formData = ref<AddBaseInfo>(cloneDeep(DEFAULT_FORM_DATA))
const defaultFormData = ref<AddBaseInfo>(cloneDeep(DEFAULT_FORM_DATA))
const initialThumbState = ref<boolean>(false) // 记录初始缩略图状态
const formRef = ref()

// 上传相关引用
const modelFile = ref() // 模型文件引用
const manualThumbFile = ref() // 手动上传的缩略图文件
const autoThumbFile = ref() // 自动生成的缩略图文件
const fileList = ref<UploadUserFile[]>([])
const UploadFileRef = ref()
const getFileName = ref()
const imageUrl = ref<string | undefined>(undefined)
const manualThumbnailUrl = ref('') // 手动上传的缩略图URL
const autoThumbnailUrl = ref('') // 自动生成的缩略图URL

// UI状态引用
const dialogVisible = ref<boolean>(false)
const isLoading = ref<boolean>(false)
const useAutoThumbnail = ref(false) // 是否使用自动生成的缩略图
const isEdit = ref<boolean>(false)
const isUpload = ref<boolean>(false)
const isThumb = ref<boolean>(true)
const pngName = ref<string | undefined>(undefined)

// 添加加载状态变量
const isGeneratingThumbnail = ref(false)
const thumbnailProgress = ref(0) // 添加进度变量
const displayProgress = ref(0) // 显示用的平滑进度值
let progressInterval: number | null = null; // 进度动画定时器ID

// 添加缩略图缓存
interface ThumbnailCacheItem {
  blob: Blob;
  url: string;
}
const thumbnailCache = new Map<string, ThumbnailCacheItem>();
// 记录当前模型ID或路径
const currentModelKey = ref<string | null>(null);

// 组件属性
interface Props {
  type: "three-model" | "milstd"
  visible: boolean
  accept: string
  detailName: string | undefined,
  isDetail?: boolean,
  id?: string
}
const props = defineProps<Props>()
const emit = defineEmits(["closeDialog"])

// 表单验证规则
const formRules: FormRules<AddBaseInfo> = {
  name: [{ required: true, trigger: "blur", message: "请输入名称" }],
  file: [{ required: props.isDetail, trigger: "change", message: "请上传文件" }]
}

/**
 * 从文件生成缩略图
 */
const generateThumbnailFromModelFile = async (file: File) => {
  if (!file) return;

  // 生成文件缓存键
  const cacheKey = `file_${file.name}_${file.size}_${file.lastModified}`;

  // 检查缓存
  if (thumbnailCache.has(cacheKey)) {
    const cachedItem = thumbnailCache.get(cacheKey);
    if (cachedItem) {
      // 使用完成回调更新UI
      onThumbnailGenerated(cachedItem.blob, cachedItem.url);
      return cachedItem.blob;
    }
  }

  try {
    // 开始生成缩略图，设置加载状态
    isGeneratingThumbnail.value = true;
    thumbnailProgress.value = 0; // 重置进度
    displayProgress.value = 0; // 重置显示进度

    // 使用支持进度回调的方法生成缩略图
    const thumbnailBlob: any = await generateThumbnailFromFileWithProgress(
      file,
      (progress) => {
        thumbnailProgress.value = progress; // 更新实际进度值

        // 平滑过渡到新进度
        smoothProgress();
      }
    );

    thumbnailBlob.fileName = getFileName.value;

    // 更新缩略图预览
    const url = URL.createObjectURL(thumbnailBlob);

    // 使用完成回调更新UI
    onThumbnailGenerated(thumbnailBlob, url);

    // 缓存生成的缩略图
    thumbnailCache.set(cacheKey, {
      blob: thumbnailBlob,
      url: url
    });
    currentModelKey.value = cacheKey;

    return thumbnailBlob;
  } catch (error) {
    handleThumbnailError(error);
    return null;
  } finally {
    // 无论成功或失败，都结束加载状态
    displayProgress.value = 100; // 确保显示进度到达100%
    setTimeout(() => {
      isGeneratingThumbnail.value = false;
    }, 500); // 延迟关闭进度条，让用户看到100%
  }
}

/**
 * 从URL生成缩略图
 */
const generateThumbnailFromModelUrl = async (path: string) => {
  if (!path) return;

  // 生成URL缓存键
  const cacheKey = `url_${path}`;

  // 检查缓存
  if (thumbnailCache.has(cacheKey)) {
    const cachedItem = thumbnailCache.get(cacheKey);
    if (cachedItem) {
      // 使用完成回调更新UI
      onThumbnailGenerated(cachedItem.blob, cachedItem.url);
      return cachedItem.blob;
    }
  }

  try {
    // 开始生成缩略图，设置加载状态
    isGeneratingThumbnail.value = true;
    thumbnailProgress.value = 0; // 重置进度
    displayProgress.value = 0; // 重置显示进度

    // 使用支持进度回调的方法生成缩略图
    const thumbnailBlob: any = await generateThumbnailFromUrlWithProgress(
      path,
      (progress) => {
        thumbnailProgress.value = progress; // 更新实际进度值

        // 平滑过渡到新进度
        smoothProgress();
      }
    );

    const fileName = getFileName.value || path.split('/').pop() || 'thumbnail.png';
    thumbnailBlob.fileName = fileName;

    // 更新缩略图预览
    const url = URL.createObjectURL(thumbnailBlob);

    // 使用完成回调更新UI
    onThumbnailGenerated(thumbnailBlob, url);

    // 缓存生成的缩略图
    thumbnailCache.set(cacheKey, {
      blob: thumbnailBlob,
      url: url
    });
    currentModelKey.value = cacheKey;

    return thumbnailBlob;
  } catch (error) {
    handleThumbnailError(error);
    return null;
  } finally {
    // 无论成功或失败，都结束加载状态
    displayProgress.value = 100; // 确保显示进度到达100%
    setTimeout(() => {
      isGeneratingThumbnail.value = false;
    }, 500); // 延迟关闭进度条，让用户看到100%
  }
}

/**
 * 平滑过渡进度值
 */
const smoothProgress = () => {
  // 如果没有平滑动画间隔，则创建一个
  if (!progressInterval) {
    progressInterval = window.setInterval(() => {
      // 如果显示进度小于实际进度，则逐渐增加
      if (displayProgress.value < thumbnailProgress.value) {
        const step = Math.max(1, Math.round((thumbnailProgress.value - displayProgress.value) / 5));
        displayProgress.value = Math.min(thumbnailProgress.value, displayProgress.value + step);
      }

      // 如果两者相等且为100，则清除间隔
      if (displayProgress.value >= 100 && thumbnailProgress.value >= 100) {
        if (progressInterval) {
          window.clearInterval(progressInterval);
          progressInterval = null;
        }
      }
    }, 50); // 每50ms更新一次
  }
}

/**
 * 处理缩略图生成错误
 */
const handleThumbnailError = (error: any) => {
  console.error('生成缩略图错误:', error);
  ElMessage.error('生成缩略图失败，请重试或手动上传缩略图');
  useAutoThumbnail.value = false;
}

/**
 * 重置所有状态
 */
const resetState = () => {
  autoThumbnailUrl.value = '';
  manualThumbnailUrl.value = '';
  formData.value = cloneDeep(DEFAULT_FORM_DATA);
  isThumb.value = true;
  useAutoThumbnail.value = false;
  isEdit.value = false;
  isUpload.value = false;
  fileList.value = [];
  imageUrl.value = undefined;
  autoThumbFile.value = undefined;
  manualThumbFile.value = undefined;
  currentModelKey.value = null;
}

/**
 * 关闭对话框
 */
const closeDialog = () => {
  emit("closeDialog", undefined);
  resetState();
}

/**
 * 对话框关闭提示
 */
function handleCloseTip(done: () => void) {
  // 判断是否有未保存的更改
  const hasFormChanges = !isEqual(defaultFormData.value, formData.value); // 表单数据是否有变化
  const hasFileUploaded = props.isDetail && fileList.value.length > 0; // 上传了新文件
  const hasThumbnailChanged = (useAutoThumbnail.value !== initialThumbState.value) || manualThumbFile.value // 缩略图状态有变化
  // 如果是详情就不判断缩略图
  if (!props.isDetail && !isEdit.value) {
    closeDialog();
    done();
  } else {
    // 如果有任何未保存的变更，提示用户
    if (hasFormChanges || hasFileUploaded || hasThumbnailChanged) {
      // 如果有未保存的变更，则提示用户是否确定关闭
      ElMessageBox.confirm("当前编辑未保存，是否确定关闭？").then(() => {
        closeDialog();
        done();
      }).catch(() => {
        // 用户取消关闭，不执行任何操作
      });
    } else {
      // 如果没有变化，直接关闭
      closeDialog();
      done();
    }
  }

}

/**
 * 表单验证
 */
const validateForm = (): boolean => {
  if (!formData.value.name) {
    ElMessage.warning("请输入名称");
    return false;
  }

  if (props.isDetail && fileList.value.length === 0) {
    ElMessage.warning("请上传模型文件");
    return false;
  }

  return true;
}

/**
 * 提交表单
 */
const handleConfirm = () => {
  if (!validateForm()) return;

  isLoading.value = true;

  // 保存
  const api = props.isDetail
    ? props.type === "three-model" ? addModelApi : addMilstdApi
    : props.type === "three-model" ? updateThreeDataApi : updateMilitaryDataApi;

  const params: FormData = props.type === "three-model" ? getModeParams() : getMilstdParams();

  api(params)
    .then((response: any) => {
      ElMessage.success(props.isDetail ? "上传成功" : "更新成功");
      emit("closeDialog", response.data);
      resetState();
    })
    .catch((error) => {
      console.error("保存失败:", error);
      ElMessage.error(props.isDetail ? "上传失败" : "更新失败");
    })
    .finally(() => {
      isLoading.value = false;
    });
}

/**
 * 获取当前使用的缩略图文件
 */
const getActiveThumbFile = () => {
  // 当开启自动生成缩略图时，使用自动生成的缩略图
  if (useAutoThumbnail.value && autoThumbFile.value) {
    return autoThumbFile.value;
  }
  // 否则使用手动上传的缩略图
  return manualThumbFile.value;
}

/**
 * 从缩略图上传组件接收文件
 */
const confirm = (val: any) => {
  manualThumbFile.value = val;
  if (val && val instanceof Blob) {
    // 只更新手动上传的缩略图URL，不影响自动生成的缩略图
    manualThumbnailUrl.value = URL.createObjectURL(val);
  }
}

/**
 * 获取三维模型表单参数
 */
const getModeParams = (): FormData => {
  const params = new FormData();
  params.append("model.name", formData.value.name);
  params.append("module", '3dmodel');

  const activeThumbFile = getActiveThumbFile();
  if (activeThumbFile) {
    params.append("thumbFile", activeThumbFile, "image.png");
  }

  if (!props.isDetail) {
    params.append("model.id", props.id as string);
    // 如果有新上传的文件
    if (fileList.value.length > 0) {
      params.append("file", fileList.value[0].raw as Blob);
    }
  } else {
    params.append("file", fileList.value[0].raw as Blob);
  }

  return params;
}

/**
 * 获取军标表单参数
 */
const getMilstdParams = (): FormData => {
  const params = new FormData();
  params.append("module", 'gjb');
  params.append("gjbInfo.name", formData.value.name);

  const activeThumbFile = getActiveThumbFile();
  if (activeThumbFile) {
    params.append("thumbFile", activeThumbFile, "image.png");
  }

  if (!props.isDetail) {
    params.append("gjbInfo.id", props.id as string);
    // 如果有新上传的文件
    if (fileList.value.length > 0) {
      params.append("file", fileList.value[0].raw as Blob);
    }
  } else {
    params.append("file", fileList.value[0].raw as Blob);
  }

  return params;
}

/**
 * 初始化对话框
 */
const showDialog = () => {
  formRef.value?.resetFields();

  // 重置表单和状态
  formData.value = cloneDeep(DEFAULT_FORM_DATA);
  formData.value.name = props.detailName || "";
  defaultFormData.value = cloneDeep(formData.value);
  fileList.value = [];
  imageUrl.value = undefined;
}

/**
 * 处理文件上传
 */
const handleFileChange: UploadProps["onChange"] = (uploadFile: any) => {
  fileList.value = [uploadFile];

  if (uploadFile.raw) {
    if (isEmpty(pngName.value)) {
      formData.value.name = uploadFile.name;
    }

    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    getFileName.value = uploadFile.name || '';
    isUpload.value = true;
    modelFile.value = uploadFile.raw;

    // 新文件上传，清除当前缓存的模型键
    currentModelKey.value = null;

    // 三维模型上传后，根据开关状态决定是否显示进度条
    if (props.type === 'three-model') {
      // 如果自动生成缩略图开关打开，则静默生成缩略图
      if (useAutoThumbnail.value) {
        generateThumbnailSilently(uploadFile.raw);
      } else {
        // 否则，显示带进度条的生成方式
        generateThumbnailFromModelFile(uploadFile.raw);
      }
    }
  }
}

/**
 * 处理文件数量超限
 */
const handleFileExceed: UploadProps["onExceed"] = (files) => {
  UploadFileRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  UploadFileRef.value?.handleStart(file);
}

/**
 * 取消编辑
 */
const handleEditCancel = async () => {
  await search();
  isEdit.value = false;
}

/**
 * 进入编辑模式
 */
const handleEdit = () => {
  isEdit.value = true;
}

/**
 * 获取详情数据
 */
const search = async () => {
  if (!props.id) return;

  const api = props.type == "three-model" ? getThreeDataApi : getMilitaryDataDetailApi;

  try {
    // 定义响应类型接口，确保包含AddBaseInfo所需的字段
    interface ApiResponse {
      data: {
        id?: string;
        name: string; // name是必需的
        code?: string;
        remark?: string;
        file?: any;
        path?: string;
        thumb?: string;
        [key: string]: any;
      }
    }

    const response = await api(props.id) as ApiResponse;
    formData.value = {
      name: response.data.name || "",
      code: response.data.code,
      remark: response.data.remark,
      file: response.data.file
    };
    imageUrl.value = response.data.path || "";

    // 如果有服务器返回的缩略图，设置为手动缩略图
    if (response.data.thumb) {
      manualThumbnailUrl.value = response.data.thumb || "";
    }

    defaultFormData.value = cloneDeep(formData.value);
    initialThumbState.value = useAutoThumbnail.value; // 记录初始缩略图状态

    // 如果是三维模型且有模型路径，根据自动生成缩略图开关决定是否显示进度条
    if (props.type === 'three-model' && response.data.path) {
      if (useAutoThumbnail.value) {
        // 如果已开启自动生成，则静默生成
        generateThumbnailUrlSilently(response.data.path);
      } else {
        // 否则使用带进度条的方式
        generateThumbnailFromModelUrl(response.data.path);
      }
    }
  } catch (error) {
    console.error("获取详情失败:", error);
    ElMessage.error("获取详情失败");
  }
}

// 生命周期钩子
onMounted(() => {
  // 初始化默认表单数据和缩略图生成器
  defaultFormData.value = cloneDeep(formData.value);
  pngName.value = props.detailName;
  thumbnailGenerator.init();
})

onBeforeUnmount(() => {
  // 组件卸载前清理Three.js资源
  thumbnailGenerator.dispose();

  // 清除进度条平滑动画定时器
  if (progressInterval) {
    window.clearInterval(progressInterval);
    progressInterval = null;
  }

  // 清除缓存的所有URL
  thumbnailCache.forEach((item) => {
    if (item.url && item.url.startsWith('blob:')) {
      URL.revokeObjectURL(item.url);
    }
  });
  thumbnailCache.clear();
})

// 监视visible属性变化
watch(
  () => [props.type, props.visible],
  () => {
    dialogVisible.value = props.visible;
    if (props.visible) {
      if (props.type == 'three-model' && props.isDetail) {
        isThumb.value = false;
      }

      nextTick(() => {
        // 确保初始化缩略图生成器
        thumbnailGenerator.init();
      });

      showDialog();

      if (!props.isDetail) {
        search();
      } else {
        // 新增模式也记录初始状态
        initialThumbState.value = useAutoThumbnail.value;
      }
    }
  },
  { immediate: true }
)

// 监视自动生成缩略图开关
watch(useAutoThumbnail, (newVal) => {
  if (newVal) {
    if (modelFile.value) {
      // 如果有上传的文件，检查是否有缓存
      const cacheKey = `file_${modelFile.value.name}_${modelFile.value.size}_${modelFile.value.lastModified}`;

      // 如果有缓存，直接使用
      if (thumbnailCache.has(cacheKey)) {
        const cachedItem = thumbnailCache.get(cacheKey);
        if (cachedItem) {
          autoThumbFile.value = cachedItem.blob;
          autoThumbnailUrl.value = cachedItem.url;
          manualThumbnailUrl.value = autoThumbnailUrl.value;
          return;
        }
      }

      // 没有缓存，且正在生成缩略图，不立即设置手动缩略图
      if (isGeneratingThumbnail.value) {
        // 不做任何操作，等待生成完成后自动设置
        return;
      }

      // 从文件生成缩略图（静默模式）
      generateThumbnailSilently(modelFile.value);
    } else if (imageUrl.value && props.type === 'three-model') {
      // 检查是否有缓存
      const cacheKey = `url_${imageUrl.value}`;

      // 如果有缓存，直接使用
      if (thumbnailCache.has(cacheKey)) {
        const cachedItem = thumbnailCache.get(cacheKey);
        if (cachedItem) {
          autoThumbFile.value = cachedItem.blob;
          autoThumbnailUrl.value = cachedItem.url;
          manualThumbnailUrl.value = autoThumbnailUrl.value;
          return;
        }
      }

      // 没有缓存，且正在生成缩略图，不立即设置手动缩略图
      if (isGeneratingThumbnail.value) {
        // 不做任何操作，等待生成完成后自动设置
        return;
      }

      // 从路径生成缩略图（静默模式）
      generateThumbnailUrlSilently(imageUrl.value);
    }
  } else {
    // 关闭自动生成缩略图时，清除manualThumbnailUrl中可能存在的自动生成URL
    // 这样thumbUpload组件就可以正确显示上传按钮而不是之前的自动缩略图
    if (manualThumbnailUrl.value && manualThumbnailUrl.value.startsWith('blob:') &&
      manualThumbnailUrl.value === autoThumbnailUrl.value) {
      manualThumbnailUrl.value = '';
    }
  }
})

// 添加一个完成回调，确保在缩略图生成完成后更新手动缩略图
const onThumbnailGenerated = (blob: Blob, url: string) => {
  // 更新自动生成的缩略图
  autoThumbFile.value = blob;
  autoThumbnailUrl.value = url;

  // 如果用户已开启自动生成缩略图，则更新手动缩略图URL
  if (useAutoThumbnail.value) {
    manualThumbnailUrl.value = url;
  }
}

/**
 * 静默生成缩略图（不显示进度条）
 */
const generateThumbnailSilently = async (file: File) => {
  if (!file) return;

  // 生成文件缓存键
  const cacheKey = `file_${file.name}_${file.size}_${file.lastModified}`;

  // 检查缓存
  if (thumbnailCache.has(cacheKey)) {
    const cachedItem = thumbnailCache.get(cacheKey);
    if (cachedItem) {
      // 使用完成回调更新UI
      onThumbnailGenerated(cachedItem.blob, cachedItem.url);
      return cachedItem.blob;
    }
  }

  try {
    // 使用生成缩略图功能，但不设置isGeneratingThumbnail为true
    const thumbnailBlob: any = await generateThumbnailFromFile(file);
    if (thumbnailBlob) {
      thumbnailBlob.fileName = getFileName.value;

      // 更新缩略图预览
      const url = URL.createObjectURL(thumbnailBlob);

      // 使用完成回调更新UI
      onThumbnailGenerated(thumbnailBlob, url);

      // 缓存生成的缩略图
      thumbnailCache.set(cacheKey, {
        blob: thumbnailBlob,
        url: url
      });
      currentModelKey.value = cacheKey;
    }
    return thumbnailBlob;
  } catch (error) {
    handleThumbnailError(error);
    return null;
  }
}

/**
 * 静默从URL生成缩略图（不显示进度条）
 */
const generateThumbnailUrlSilently = async (path: string) => {
  if (!path) return;

  // 生成URL缓存键
  const cacheKey = `url_${path}`;

  // 检查缓存
  if (thumbnailCache.has(cacheKey)) {
    const cachedItem = thumbnailCache.get(cacheKey);
    if (cachedItem) {
      // 使用完成回调更新UI
      onThumbnailGenerated(cachedItem.blob, cachedItem.url);
      return cachedItem.blob;
    }
  }

  try {
    // 使用生成缩略图功能，但不设置isGeneratingThumbnail为true
    const thumbnailBlob: any = await generateThumbnailFromUrl(path);
    if (thumbnailBlob) {
      const fileName = getFileName.value || path.split('/').pop() || 'thumbnail.png';
      thumbnailBlob.fileName = fileName;

      // 更新缩略图预览
      const url = URL.createObjectURL(thumbnailBlob);

      // 使用完成回调更新UI
      onThumbnailGenerated(thumbnailBlob, url);

      // 缓存生成的缩略图
      thumbnailCache.set(cacheKey, {
        blob: thumbnailBlob,
        url: url
      });
      currentModelKey.value = cacheKey;
    }
    return thumbnailBlob;
  } catch (error) {
    handleThumbnailError(error);
    return null;
  }
}
</script>

<template>
  <el-drawer v-model="dialogVisible" direction="rtl" :show-close="false" :before-close="handleCloseTip" size="800"
    :append-to-body="true" @close-auto-focus="closeDialog" @close="closeDialog">
    <template #header>
      <h4 v-if="isDetail">上传{{ type == "milstd" ? "军标" : "三维模型" }}</h4>
      <h4 v-else>{{ type == "milstd" ? "军标" : "三维模型" }}详情</h4>
      <el-space justify="end">
        <!-- 详情页面 -->
        <template v-if="!isDetail">
          <!-- 编辑状态：显示取消保存和保存按钮 -->
          <el-button v-if="isEdit" @click="handleEditCancel">
            取消保存
          </el-button>
          <el-button v-if="isEdit" type="primary" :loading="isLoading" v-throttle="() => handleConfirm()">
            保存
          </el-button>
          <!-- 非编辑状态：显示编辑按钮 -->
          <el-button v-if="!isEdit" type="primary" @click="handleEdit">
            编辑
          </el-button>
        </template>

        <!-- 上传页面：只显示保存按钮 -->
        <template v-else>
          <el-button type="primary" :loading="isLoading" v-throttle="() => handleConfirm()">
            保存
          </el-button>
        </template>
      </el-space>
    </template>
    <template #default>
      <el-form ref="formRef" v-if="isDetail || isEdit" :model="formData" :rules="formRules" inline width="600"
        label-width="140px" label-position="right" :close-on-click-modal="false"
        element-loading-background="rgba(245, 247, 250, 0.8)">
        <el-row :gutter="20">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" autocomplete="off" placeholder="请输入" style="width: 520px"
              @change="pngName = formData.name" />
          </el-form-item>
        </el-row>
        <el-row>
          <!-- 模型上传区域 -->
          <el-form-item :label="type == 'milstd' ? '军标' : '三维模型'" prop="file">
            <el-upload ref="UploadFileRef" class="avatar-uploader" v-model:file-list="fileList" :limit="1"
              :show-file-list="false" :accept="accept" :auto-upload="false" :on-exceed="handleFileExceed"
              :on-change="handleFileChange">
              <!-- 图片预览区域 -->
              <template v-if="imageUrl">
                <!-- 三维模型且有自动生成的缩略图 -->
                <img v-if="type == 'three-model' && autoThumbnailUrl && !isUpload" :src="autoThumbnailUrl"
                  class="avatar" />
                <!-- 生成缩略图进度条 -->
                <div v-else-if="type == 'three-model' && isGeneratingThumbnail" class="avatar-uploader-icon">
                  <el-progress type="circle" :percentage="displayProgress"
                    :status="displayProgress < 100 ? 'success' : 'success'" :indeterminate="false" :width="120"
                    :stroke-width="8">
                    <span class="progress-text">{{ displayProgress < 100 ? '生成缩略图中...' : '生成完成' }}</span>
                        <div class="progress-percent">{{ displayProgress }}%</div>
                  </el-progress>
                </div>
                <!-- 详情图片 -->
                <img v-else-if="!isUpload" :src="`/model-api${imageUrl}`" class="avatar" />
                <!-- 上传后的图片/自动生成的缩略图 -->
                <img v-else-if="type == 'three-model' && autoThumbnailUrl" :src="autoThumbnailUrl" class="avatar" />
                <!-- 生成缩略图进度条（上传后） -->
                <div v-else-if="type == 'three-model' && isGeneratingThumbnail" class="avatar-uploader-icon">
                  <el-progress type="circle" :percentage="displayProgress"
                    :status="displayProgress < 100 ? 'success' : 'success'" :indeterminate="false" :width="120"
                    :stroke-width="8">
                    <span class="progress-text">{{ displayProgress < 100 ? '生成缩略图中...' : '生成完成' }}</span>
                        <div class="progress-percent">{{ displayProgress }}%</div>
                  </el-progress>
                </div>
                <!-- 上传后的图片 -->
                <img v-else :src="imageUrl" class="avatar" />
              </template>
              <!-- 上传按钮 -->
              <div v-else class="avatar-uploader-icon">
                <el-icon>
                  <Plus />
                </el-icon>
                <span class="describe">点击上传{{ type == "milstd" ? "军标" : "三维模型" }}</span>
              </div>
            </el-upload>
            <!-- 手动上传缩略图组件 -->
            <el-form-item label="缩略图" v-if="type !== 'milstd'">
              <thumbUpload :Url="manualThumbnailUrl" :isDisabled="useAutoThumbnail" @confirm="confirm" />
            </el-form-item>
          </el-form-item>

          <!-- 缩略图区域（仅三维模型需要） -->
          <template v-if="type !== 'milstd'">
            <!-- 缩略图选项 -->
            <el-form-item label="使用生成的缩略图">
              <el-switch v-model="useAutoThumbnail" />
            </el-form-item>
          </template>
        </el-row>
      </el-form>

      <!-- 只读模式下的表单 -->
      <el-form v-else :model="formData" inline width="600" label-width="140px" label-position="right"
        :close-on-click-modal="false" element-loading-background="rgba(245, 247, 250, 0.8)">
        <el-form-item label="名称" prop="name">
          {{ formData.name }}
        </el-form-item>
        <el-row>
          <el-form-item :label="type == 'milstd' ? '军标' : '三维模型'" prop="file">
            <el-upload ref="UploadFileRef" class="avatar-uploader" disabled v-model:file-list="fileList" :limit="1"
              :show-file-list="false" :accept="accept" :auto-upload="false">
              <!-- 只读模式 三维模型预览 -->
              <!-- 三维模型且有自动生成的缩略图 -->
              <img v-if="type == 'three-model' && autoThumbnailUrl" :src="autoThumbnailUrl" class="avatar" />
              <!-- 生成缩略图进度条 -->
              <div v-else-if="type == 'three-model' && isGeneratingThumbnail" class="avatar-uploader-icon">
                <el-progress type="circle" :percentage="displayProgress"
                  :status="displayProgress < 100 ? 'success' : 'success'" :indeterminate="false" :width="120"
                  :stroke-width="8">
                  <span class="progress-text">{{ displayProgress < 100 ? '生成缩略图中...' : '生成完成' }}</span>
                      <div class="progress-percent">{{ displayProgress }}%</div>
                </el-progress>
              </div>
              <!-- 普通图片 -->
              <img v-else-if="imageUrl" :src="`/model-api${imageUrl}`" class="avatar" />
              <div v-else class="avatar-uploader-icon">
                <span class="describe">无可用图片</span>
              </div>
            </el-upload>
            <el-form-item label="缩略图" v-if="type !== 'milstd'">
              <!-- 根据自动生成开关状态显示对应缩略图 -->
              <template v-if="useAutoThumbnail">
                <img v-if="autoThumbnailUrl" :src="autoThumbnailUrl" style="width: 178px;height: 178px;"
                  class="avatar" />
                <div v-else class="avatar-uploader-icon">
                  <span class="describe">无自动缩略图</span>
                </div>
              </template>
              <template v-else>
                <img v-if="manualThumbnailUrl"
                  :src="manualThumbnailUrl.startsWith('blob:') ? manualThumbnailUrl : `/model-api${manualThumbnailUrl}`"
                  style="width: 178px;height: 178px;" class="avatar" />
                <div v-else class="avatar-uploader-icon">
                  <span class="describe">无缩略图</span>
                </div>
              </template>
            </el-form-item>
          </el-form-item>
          <template v-if="type !== 'milstd'">
            <el-form-item label="使用生成的缩略图">
              <el-switch disabled v-model="useAutoThumbnail" />
            </el-form-item>
          </template>
        </el-row>
      </el-form>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button plain @click="closeDialog">关 闭</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.progress-text {
  display: inline-block;
  margin-top: 0;
  font-size: 14px;
  color: #67C23A;
}

.progress-percent {
  font-size: 18px;
  font-weight: bold;
  margin-top: 5px;
  color: #67C23A;
}
</style>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #409EFF;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background-color: #ECF5FF;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20px;
  width: 178px;
  height: 178px;

  .el-icon {
    font-size: 28px;
    color: #8c939d;
  }

  .describe {
    color: #409EFF;
  }
}
</style>
